import React, { useState, useRef, useEffect } from 'react'
import styles from './index.module.scss'

export default function Textarea({
  maxLength = 100,
  value,
  onChange,
  ...rest
}) {
  const [content, setContent] = useState(value || '')
  const handelChange = (e) => {
    setContent(e.target.value)
    onChange && onChange(e)
  }
  // 自动获取光标
  const textRef = useRef(null)
  useEffect(() => {
    textRef.current.focus()
    // 设置自动获取光标位置
    textRef.current.setSelectionRange(-1, -1)
  },[])

  return (
    <div className={styles.root}>
      {/* 文本输入框 */}
      <textarea
        ref={textRef}
        className="textarea"
        maxLength={maxLength}
        value={value}
        {...rest}
        onChange={handelChange}
      ></textarea>
      {/* 当前字数/最大允许字数 */}
      <div className="count">
        {content.length}/{maxLength}
      </div>
    </div>
  )
}
